import { ref } from 'vue'

export function useCategoryForm() {
  const dialogFormVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')
  const formData = ref<any>({
    name: '',
    courseCount: '',
    description: '',
    level: '',
    order: '',
    parent: '',
    parentId: ''
  })
  const currentParent = ref<any>(null)
  const currentEditId = ref<string | null>(null)

  const rules = {
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  }

  function cleanFormData(data: any) {
    const result: any = {}
    const forbiddenFields = ['objectId', 'createdAt', 'updatedAt']
    Object.keys(data).forEach(key => {
      if (
        data[key] !== '' &&
        data[key] !== undefined &&
        data[key] !== null &&
        !forbiddenFields.includes(key)
      ) {
        result[key] = data[key]
      }
    })
    return result
  }

  //打开添加分类的表单弹窗
  function openAddForm(parent?: any) {
    dialogType.value = 'add'
    dialogFormVisible.value = true
    formData.value = {
      name: '',
      courseCount: '',
      description: '',
      level: parent ? (parseInt(parent.level || '1') + 1).toString() : '1',
      order: '',
      parent: parent?.name || '',
      parentId: parent?.objectId || ''
    }
    currentParent.value = parent || null
    currentEditId.value = null
  }

  //打开编辑弹窗
  function openEditForm(row: any) {
    dialogType.value = 'edit'
    dialogFormVisible.value = true
    formData.value = {
      name: row.name,
      courseCount: row.courseCount,
      description: row.description,
      level: row.level,
      order: row.order,
      parent: row.parent,
      parentId: row.parentId
    }
    currentEditId.value = row.objectId
  }

  //重置表单数据和相关状态
  function resetForm() {
    formData.value = {
      name: '',
      courseCount: '',
      description: '',
      level: '',
      order: '',
      parent: '',
      parentId: ''
    }
    currentParent.value = null
    currentEditId.value = null
  }

  return {
    dialogFormVisible,
    dialogType,
    formData,
    rules,
    currentEditId,
    cleanFormData,
    openAddForm,
    openEditForm,
    resetForm
  }
}